package com.loopj.ohos.http.sample;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.RequestHandle;
import com.loopj.ohos.http.ResponseHandlerInterface;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.auth.AuthScope;
import cz.msebera.android.httpclient.auth.UsernamePasswordCredentials;
import ohos.aafwk.content.Intent;
import ohos.agp.components.TextField;
import ohos.utils.net.Uri;

/**
 * DigestAuthSample
 */
public class DigestAuthSample extends GetSample {

    private TextField usernameField;
    private TextField passwordField;

    @Override
    public String getDefaultURL() {
        return PROTOCOL + "httpbin.org/digest-auth/auth/user/passwd2";
    }

    @Override
    public int getSampleTitle() {
        return ResourceTable.String_title_digest_auth;
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        usernameField = new TextField(this);
        passwordField = new TextField(this);
        usernameField.setHint("Username");
        passwordField.setHint("Password");
        usernameField.setText("user");
        passwordField.setText("passwd2");
        customFieldsLayout.addComponent(usernameField);
        customFieldsLayout.addComponent(passwordField);
    }

    @Override
    public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) {
        setCredentials(client, URL);
        return client.get(this, URL, headers, null, responseHandler);
}

    @Override
    public boolean isCancelButtonAllowed() {
        return true;
    }

    @Override
    public boolean isRequestHeadersAllowed() {
        return true;
    }

    @Override
    public boolean isRequestBodyAllowed() {
        return false;
    }

    private void setCredentials(AsyncHttpClient client, String URL) {
        Uri parsed = Uri.parse(URL);
        client.clearCredentialsProvider();
        client.setCredentials(
                new AuthScope(parsed.getDecodedHost(), parsed.getPort() == -1 ? 80 : parsed.getPort()),
                new UsernamePasswordCredentials(
                        usernameField.getText().toString(),
                        passwordField.getText().toString()
                )
        );
    }
}
